package com.tbox.tbsdk;

import android.text.TextUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * describe: AES加密算法
 */

class AesUtil {

    /*
     * 加密
     */
    public static byte[] encryptUTF8String(String cleartext, String secretKey) {
        if (TextUtils.isEmpty(cleartext)) {
            return new byte[]{};
        }
        try {
            byte[] result = doEncryptUTF8String(secretKey, cleartext);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] doEncryptUTF8String(String password, String clear) throws Exception {
        // 创建AES秘钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(password.getBytes(), "AES");
        // 创建密码器
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 初始化加密器
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        // 加密
        return cipher.doFinal(clear.getBytes("UTF-8"));
    }

    public static byte[] encrypt(byte[] bytes, String secretKey) {
        if (bytes == null || bytes.length == 0) {
            return new byte[]{};
        }
        try {
            byte[] result = doEncrypt(secretKey, bytes);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] doEncrypt(String password, byte[] bytes) throws Exception {
        // 创建AES秘钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(password.getBytes(), "AES");
        // 创建密码器
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 初始化加密器
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        // 加密
        return cipher.doFinal(bytes);
    }

    /*
     * 解密
     */
    public static byte[] decrypt(byte[] content, String secretKey) {
        try {
            byte[] result = doDecrypt(content, secretKey);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] doDecrypt(byte[] content, String secretKey) throws Exception {
        // 创建AES秘钥
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "AES");
        // 创建密码器
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        // 初始化解密器
        cipher.init(Cipher.DECRYPT_MODE, key);
        // 解密
        return cipher.doFinal(content);
    }

}